import { _decorator, Component, Node } from 'cc';
import { CocosUtils } from '../../../../Framework/Scripts/Utils/CocosUtils';
import { State, WSConnectedEvent, WSRecvDataEvent } from '../../../../Framework/Scripts/Managers/Net/NetCfg';
import { UIMgr, UIType } from '../../../../Framework/Scripts/Managers/UIMgr';
import { AbNames, EventMsgKes } from '../../Config/ResConfig';
import { encodeMsg, Msg } from '../../../AssetPackage/Props/DT';
import { Cmd, Stype } from '../../Config/GameCfg';
import { GameData } from '../../Data/GameData';
import {  decodeDailyChallengeCfgRes, decodeDailyChallengeRes, decodeGamePlayTzRes, decodeGameTzAddCountRes } from '../../../AssetPackage/Props/Hall/Game/GameTZ';
import { decodeGetHD5_PrizeDrawListReq, decodeGetHD5_PrizeDrawListRes, decodeGetHD5_PrizeDrawOptReq, decodeGetHD5PrizeDrawOptRes, encodeGetHD5_PrizeDrawListReq, encodeGetHD5_PrizeDrawOptReq, GetHD5_PrizeDrawListReq, GetHD5_PrizeDrawOptReq } from '../../../AssetPackage/Props/Hall/GetHD5PrizeDraw';
import { decodeGetHD_LoginRewardGetReq, decodeGetHD_LoginRewardGetRes, decodeGetHD_LoginRewardReq, decodeGetHD_LoginRewardRes, encodeGetHD_LoginRewardGetReq, encodeGetHD_LoginRewardReq, GetHD_LoginRewardGetReq, GetHD_LoginRewardReq } from '../../../AssetPackage/Props/Hall/GetHDLoginReward';
import { decodeGetUserInfoReq, encodeGetUserInfoReq, GetUserInfoReq } from '../../../AssetPackage/Props/Hall/GetUserInfo';
import { FriendJoinOperateReq, FriendStartPKReq } from '../../../AssetPackage/Props/Game/DT_PK';
import { IChouJiangCfgReq, IChouJiangCfgRes, IChouJiangOptReq, IChouJiangOptRes, IDailyChallengeCfgRes, IDailyChallengeReq, IDailyChallengeRes, IDcAddCountRes, IDcStartReq, IDcStartRes, IGamePlayTzReq, IGetUserInfoReq, IGetUserInfoRes, IHallRes, IMsgReq, IRewards, IThemeMatchPPBroad, IThemeMatchPPRes, IThemeMatchRes, IThemeMatchStopPPRes } from './GameHallProto';
import { IComRes, IUserInfo } from '../../Config/CommonProto';
import { CmdHall } from './CmdHall';
import { ICall } from '../../../../Framework/Scripts/Managers/SceneMgr';
const { ccclass, property } = _decorator;

@ccclass('GameHallMsg')
export class GameHallMsg extends Component {
    net: any;
    url: string;
    connectCall: ICall = null;
    start() {
        // this.InitUI();
        // this.InitData();

    }

    update(deltaTime: number) {
        if(this.net.state === State.Invalid) {
            return;
        }
        if(this.net.state === State.Disconnected) {
            console.log('=====大厅服务重新连接==========')
            this.net.connectServer( this.url);
        }
    }

    protected onDestroy(): void {
        this.unRegisterEvent();
    }

    
    public ConnectHall(ip,port){
        this.InitUI();
        this.InitData();

        this.url = CocosUtils.getUrlByIdAndPort(ip,port);
        console.log('======开始链接大厅服务=======',this.url);
        this.net = new globalThis.gameMgr.WsMgr();
        this.net.connectServer(this.url);
    }

    
    //设置连接成功的回调
    public SetConectCall(call:ICall){
        this.connectCall = call;
    }

    private InitUI(){
        this.registerEvent();       
    }

    private InitData(){
        globalThis.gameMgr._GameHallMsg = this;
    }

    private registerEvent(){
        globalThis.gameMgr._eventTarget.on(WSConnectedEvent,this.onConnectHallServer,this);
        globalThis.gameMgr._eventTarget.on(WSRecvDataEvent,this.onRevHallData,this);
    }

    private unRegisterEvent(){
        globalThis.gameMgr._eventTarget.off(WSConnectedEvent,this.onConnectHallServer,this);
        globalThis.gameMgr._eventTarget.on(WSRecvDataEvent,this.onRevHallData,this);
    }

    //发送二进制数据
    private _sendMsg(ctype: number, uint8Array: Uint8Array) {
        let msg: Msg = {
            stype: Stype.Hall,
            ctype: ctype,
            buffer: uint8Array,
        };
        //编码协议数据
        let buf: Uint8Array = encodeMsg(msg);

        //去掉数据编码产生的0
        let str = buf.toString();
        let arr = str.split(',');
        let arr2 = []
        arr.forEach(element => {
            arr2.push(parseInt(element));
        });
        const uint8Array1 = new Uint8Array(arr2);
        console.warn('=========hall _sendMsg========', ctype);
        let arrbuffer = uint8Array1.buffer;
        this.net.SendData(arrbuffer);
    }

    //发送JSON数据
    private _sendJson(type: number, data: any){
        console.log('=======_sendJson======',type,data);
        if(this.net)
            this.net.sendJsonData(type,data);
    }

    //大厅服务网络连接成功
    private onConnectHallServer(data){
        console.log('=======onConnectHallServer===========');

        //在_root 常驻节点上添加一个 大厅的MassAge
        let root = globalThis.gameMgr._rootNode;
        if(!root.getComponent('GameHallCom')){
            root.addComponent('GameHallCom');
        }
        // 

        if(this.connectCall){
            let callBack = this.connectCall.func;
            let path = this.connectCall.path;
            callBack(path)
        }
        // this.connectCall && this.connectCall();
    }

     /**
     * 请求大厅数据 1
     */
     public GameHallReq() {
        let req:IMsgReq = {
            userId: GameData.inst.userInfo.userId
        }
        console.log('=====GameHallReq=======',req);
        this._sendJson(CmdHall.GetHallReq,req);
    }

    // 获取新用户奖励数据 1
    public GetUserRewardReq() {
        let req: IMsgReq = {
            userId: GameData.inst.userInfo.userId,
        }
        console.log('=====GetUserRewardReq=======',req);
        this._sendJson(CmdHall.GetUserRewardReq,req);
    }

    /**
    * 领取新用户奖励 1
    */
    public GetNewPlayerReq() {
        let req: IMsgReq = {
            userId: GameData.inst.userInfo.userId,
        }
        console.log('=====GetNewPlayerReq=======',req);
        this._sendJson(CmdHall.GetNewPlayerReq,req);
    }

    /**
    * 获取用户信息
    */
    public GetUserInfoReq() {
        let req: IGetUserInfoReq = {
            userId: GameData.inst.userInfo.userId
        }
        console.log('=====GetNewPlayerReq=======',req);
        this._sendJson(CmdHall.GetUserInfoReq,req);
    }


    /**
     * 获取惊喜宝箱
     */
    public GetHD_SurpriseChestReq() {

    }

    /**
     * 获取每周登录奖励
     */
    public GetHD_LoginRewardReq() {
        let req: GetHD_LoginRewardReq ={
            userId: GameData.inst.userInfo.userId
        }
        let uint8Array: Uint8Array = encodeGetHD_LoginRewardReq(req);
        console.log("======GetHD_LoginRewardReq 编码======", uint8Array);
        console.log('======GetHD_LoginRewardReq 解码======', decodeGetHD_LoginRewardReq(uint8Array));
        this._sendMsg(Cmd.Hall.GetHD_LoginRewardReq, uint8Array);
    }

    /**
     * 领取每周登录奖励
     */
    public GetHD_LoginRewardGetReq() {
        let req:GetHD_LoginRewardGetReq = {
            userId: GameData.inst.userInfo.userId,
        }
        let uint8Array: Uint8Array = encodeGetHD_LoginRewardGetReq(req);
        console.log("======GetHD_LoginRewardGetReq 编码======", uint8Array);
        console.log('======GetHD_LoginRewardGetReq 解码======', decodeGetHD_LoginRewardGetReq(uint8Array));
        this._sendMsg(Cmd.Hall.GetHD_LoginRewardGetReq, uint8Array);
    }

    /**
     * 获取幸运抽奖配置
     */
    public GetHD5_PrizeDrawCfgReq() {
        let req: IChouJiangCfgReq = {
            userId: GameData.inst.userInfo.userId,
        }
        console.log('======获取幸运抽奖配置请求=======');
        this._sendJson(CmdHall.GetHD5_PrizeDrawListReq,req);
    }

    /**
     * 幸运抽奖操作 free = 1扣费 2 免费 
     */
    public GetHD5_PrizeDrawOptReq(pot: number,free: number = 1) {
        let req: IChouJiangOptReq = {
            userId: GameData.inst.userInfo.userId,
            count: pot,
            isFree: free
        }
        console.log('======幸运抽奖操作请求=======');
        this._sendJson(CmdHall.GetHD5_PrizeDrawOptReq,req);
    }


    //======================每日挑战大厅start=======================
    //请求每日挑战配置
    public DailyChallengeCfgReq() {
        let req: IMsgReq = {
            userId: GameData.inst.userInfo.userId,
        }
        console.log('========DailyChallengeCfgReq=======',req);
        this._sendJson(CmdHall.DailyChallengeCfgReq, req);
    }

    //每日挑战具体配置
    public DailyChallengeReq(dcType: number) {
        console.log('=======DailyChallengeReq===========', dcType);
        let req: IDailyChallengeReq = {
            dcType: dcType,
            userId: GameData.inst.userInfo.userId,
        }
        this._sendJson(CmdHall.DailyChallengeReq, req);
    }

    //每日挑战--看视频获取挑战机会
    public GameTzAddCountReq() {
        let req: IMsgReq = {
            userId: GameData.inst.userInfo.userId,
        }
        this._sendJson(CmdHall.GameTzAddCountReq, req);
    }

    //开始游戏
    public GamePlayTzReq(dcType: number) {
        let req: IGamePlayTzReq = {
            userId: GameData.inst.userInfo.userId,
            dcType: dcType
        }
        this._sendJson(CmdHall.GamePlayTzReq, req);
    }
    //======================每日挑战大厅start=======================

    /**
     * 用户加入操作
     * @param opt  1 是加入 2 是拒绝
     */
    public FriendJoinOperateReq(opt: number) {
        let d: FriendJoinOperateReq = {
            userId: GameData.inst.userInfo.userId,
            operate: opt
        }
    }
    //请求好友pk
    public FriendStartPKReq() {
        let d: FriendStartPKReq = {
            userId: GameData.inst.userInfo.userId,
        }

    }

    //请求主题赛配置
    public ThemeMatchReq(){
        let req:IMsgReq = {
            userId: GameData.inst.userInfo.userId,
        }
        this._sendJson(CmdHall.ThemeMatchReq, req);
    }

    //主题赛开始匹配
    public ThemeMatchPPReq(dwType: number){
        let req:IMsgReq = {
            userId: GameData.inst.userInfo.userId,
            type: dwType
        }
        this._sendJson(CmdHall.ThemeMatchPPReq, req);
    }

    //主题赛取消匹配
    public ThemeMatchPPStopReq(){
        let req:IMsgReq = {
            userId: GameData.inst.userInfo.userId,
            type:globalThis.gameMgr.zts_type
        }
        this._sendJson(CmdHall.ThemeMatchPPStopReq, req);
    }

    //收到大厅服务数据
    private onRevHallData(binaryData){
        console.log('=======onRevHallData===========',binaryData);
        let msg = JSON.parse(binaryData);
        let ctype = msg.type;
        let data = msg.data;
        this._onMsg(ctype,data);
    }

    private _onMsg(ctype: number, msg: any) {
        console.log('=====GameHallMsg==_onMsg========',ctype);
        switch (ctype) {
            case CmdHall.GetHallReq:   //大厅配置返回 1
                this.onMsgGetHallRes(msg);
                break;
            case CmdHall.GetUserRewardReq: //获取新用户的奖励数据 1
                this.onMsgGetUserRewardRes(msg);
                break;
            case CmdHall.GetNewPlayerReq:      //领取新用户奖励 1
                this.onMsgGetNewPlayerRes(msg);
                break;
            case CmdHall.UpdateUserInfoNotice: //用户数据发生变化 1
                this.onMsgUpdateUserInfoNotice(msg);
                break;
            case CmdHall.GetUserInfoReq:   //获取用户数据  
                this.onGetUserInfoRes(msg);
                break;

            case Cmd.Hall.GetHD_LoginRewardRes: //活动--每周登录奖励配置返回
                this.onGetHDLoginRewardRes(msg);
                break;  
            case Cmd.Hall.GetHD_LoginRewardGetRes: //活动--领取每周登录奖励返回
                this.onGetHDLoginRewardGetRes(msg);
                break;

            case Cmd.Hall.GetHD5_PrizeDrawListReq: //幸运抽奖配置
                this.onGetHD5PrizeDrawListRes(msg);
                break;
            case Cmd.Hall.GetHD5_PrizeDrawOptReq://幸运抽奖操作
                this.onGetHD5PrizeDrawOptRes(msg);
                break;

            case CmdHall.DailyChallengeCfgReq: //每日挑战--配置
                this.onDailyChallengeCfgRes(msg);
                break;
            case CmdHall.DailyChallengeReq: //每日挑战--具体选择
                this.onDailyChallengeRes(msg);
                break;
            case CmdHall.GameTzAddCountReq: //每日挑战--看视频添加挑战次数
                this.onGameTzAddCountRes(msg);
                break;
            case CmdHall.GamePlayTzReq: //挑战赛--开始游戏
                this.onGamePlayTzRes(msg);
                break;


            case CmdHall.ThemeMatchReq: //主题赛-- 配置
                this.onThemeMatchRes(msg);
                break;    
            case CmdHall.ThemeMatchPPReq: //主题赛-- 开始匹配
                this.onThemeMatchPPRes(msg);
                break;       
            case CmdHall.ThemeMatchPPStopReq://主题赛-- 停止匹配
                this.onThemeMatchPPStopRes(msg);
                break;    
            case CmdHall.ThemeMatchPPBroad://主题赛 -- 匹配到了的广播 直接开始有
                this.onThemeMatchPPBroad(msg);
                break; 
            case CmdHall.ThemeMatchStarReq: //主题赛 --开始游戏（准备）
                this.onThemeMatchStarRes(msg);
                break; 
            case CmdHall.ThemeMatchStarBroad: //主题赛 --开始游戏广播
                this.onThemeMatchStarBroad(msg);
                break;
            case CmdHall.ThemeMatchJieSanBroad: //玩家取消匹配，广播结果
                this.onThemeMatchJieSanBroad(msg);
                break;    
                
    
            default:
                break;
        }
    }


    //请求大厅数据返回 1
    private onMsgGetHallRes(data: IHallRes | any): void {
        console.log('onMsgGetHallRes = ', data);
        if (data.gameNet) {
            GameData.inst.gameNetCfg = data.gameNet;
            //保存服务的ip和端口
            globalThis.gameMgr.gameNet = data.gameNet;
        }
        if (data.userInfo) {
            GameData.inst.setUserInfo(data.userInfo);
        }
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGameHallRes, data);
    }

    // 获取新用户的奖励数据 1
    private onMsgGetUserRewardRes(data: IRewards| any): void {
        console.log('onMsgGetUserRewardRes = ', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGetUserRewardRes, data);
    }

    //领取新用户奖励 1
    private onMsgGetNewPlayerRes(data: IComRes | any): void {
        console.log('onMsgGetNewPlayerRes = ', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGetNewPlayerRes, data);
    }

    //用户数据发生变化 1
    private onMsgUpdateUserInfoNotice(data: IUserInfo | any): void {
        console.log('onMsgUpdateUserInfoNotice = ', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgUpdateUserInfoNotice, data);
    }

    //获取用户数据
    private onGetUserInfoRes(data: IGetUserInfoRes): void {
        console.log('onGetUserInfoRes = ', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGetUserInfoRes, data);
    }

    //活动 -- 每周登录奖励
    private onGetHDLoginRewardRes(buffer: Uint8Array): void{
        let data = decodeGetHD_LoginRewardRes(buffer);
        console.log('========onGetHDLoginRewardRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgonGetHD_LoginRewardRes,data);
    }
   //活动 -- 领取每周登录奖励
    private onGetHDLoginRewardGetRes(buffer:Uint8Array): void{
        let data = decodeGetHD_LoginRewardGetRes(buffer);
        console.log('========onGetHDLoginRewardGetRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGetHD_LoginRewardGetRes, data);
    }

    //幸运抽奖配置
    private onGetHD5PrizeDrawListRes(data: IChouJiangCfgRes): void {
        console.log('========onGetHD5PrizeDrawListRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGetHD5_PrizeDrawListRes, data);
    }

    // 幸运抽奖操作
    private onGetHD5PrizeDrawOptRes(data: IChouJiangOptRes): void {
        console.log('========onGetHD5PrizeDrawOptRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGetHD5_PrizeDrawOptRes, data);
    }

    // 每日挑战配置 
    private onDailyChallengeCfgRes(data: IDailyChallengeCfgRes): void {
        console.log('========onDailyChallengeCfgRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgDailyChallengeCfgRes, data);
    }

    // 每日挑战具体选择
    private onDailyChallengeRes(data: IDailyChallengeRes): void {
        console.log('========onDailyChallengeRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgDailyChallengeRes, data);
    }

    // 每日挑战--看视频添加挑战次数
    private onGameTzAddCountRes(data: IDcAddCountRes): void {
        console.log('========onGameTzAddCountRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGameTzAddCountRes, data);
    }

    // 挑战赛开始游戏
    private onGamePlayTzRes(data: IDcStartRes): void {
        console.log('========onGamePlayTzRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgGamePlayTzRes, data);
    }

    //主题赛-- 配置
    private onThemeMatchRes(data:IThemeMatchRes|any): void{
        console.log('========onThemeMatchRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchRes, data);
    }

    //主题赛-- 开始匹配
    private onThemeMatchPPRes(data:IThemeMatchPPRes):void{
        console.log('========onThemeMatchPPRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchPPRes, data);
    }

    // 主题赛-- 停止匹配
    private onThemeMatchPPStopRes(data:IThemeMatchStopPPRes): void{
        console.log('========onThemeMatchPPRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchPPStopRes, data);
    }

    //主题赛 -- 匹配到了的广播
    private onThemeMatchPPBroad(data:IThemeMatchPPBroad): void{
        console.log('========onThemeMatchPPBroad=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgIThemeMatchPPBroad, data);
    }

    // 主题赛 --开始游戏（相当于用户准备）
    private onThemeMatchStarRes(data:any): void{
        console.log('========onThemeMatchStarRes=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchStarRes, data);
    }

    // 主题赛 --开始游戏广播 两个用户都准备了广播
    private onThemeMatchStarBroad(data:any): void{
        console.log('========onThemeMatchStarBroad=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchStarBroad, data);
    }

    //玩家取消匹配，广播结果
    private onThemeMatchJieSanBroad(data: any){
        console.log('========onThemeMatchJieSanBroad=============', data);
        globalThis.gameMgr._eventTarget.emit(EventMsgKes.msgThemeMatchJieSanBroad, data);
    }
}


